import datetime
import uuid

from django.db.models import Q
from django.shortcuts import render, redirect
from web.forms import account
from django.http import JsonResponse, HttpResponse
from web.models import UserInfo, Transaction, PricePolicy


def register(request):
    if request.method == 'GET':
        form = account.RegisterModelForm()
        return render(request, "register.html", {"form": form})
    form = account.RegisterModelForm(data=request.POST)
    if form.is_valid():
        instance = form.save()
        policy_object = PricePolicy.objects.filter(category=1, title='个人免费版').first()
        Transaction.objects.create(status=2, order=uuid.uuid4(), user=instance,
                                   price_policy=policy_object,
                                   count=0, price=0,
                                   start_datetime=datetime.datetime.now())
        return JsonResponse({'status': True, 'data': '/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    form = account.SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    if request.method == 'GET':
        form = account.LoginSMSForm()
        return render(request, "login_sms.html", {"form": form})
    form = account.LoginSMSForm(request.POST)
    if form.is_valid():
        user = form.cleaned_data['mobile_phone']
        request.session['user_id'] = user.id
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({'status': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    if request.method == 'GET':
        form = account.LoginForm(request)
        return render(request, "login.html", {"form": form})
    form = account.LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user = (UserInfo.objects.filter(Q(username=username) | Q(mobile_phone=username))
                .filter(password=password).first())
        if user:
            request.session['user_id'] = user.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('/index')
        form.add_error('username', '账号或密码错误')
    return render(request, 'login.html', {"form": form})


def image_code(request):
    from io import BytesIO
    from utils.image_code import check_code

    img, code = check_code()
    request.session['image_code'] = code
    request.session.set_expiry(60)
    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())
